package com.seeTools.boot.pc.controller.sys;

import cn.hutool.core.util.StrUtil;
import com.seeTools.boot.api.bo.sys.LoginRequest;
import com.seeTools.boot.api.entity.sys.SysTokenInfo;
import com.seeTools.boot.api.entity.sys.SysUser;
import com.seeTools.boot.common.constant.Constants;
import com.seeTools.boot.common.core.Result;
import com.seeTools.boot.pc.bo.sys.SysConstant;
import com.seeTools.boot.pc.conf.ThreadLocalHolder;
import com.seeTools.boot.pc.service.sys.ISysLoginService;
import com.seeTools.boot.pc.service.sys.SysConfigService;
import com.seeTools.boot.pc.service.sys.SysOssConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * @author xiaotong
 */
@Slf4j
@RestController
@RequestMapping("/api/login")
public class LoginController {

    @Resource
    private ISysLoginService iSysLoginService;
    @Resource
    private SysOssConfigService sysOssConfigService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private SysConfigService sysConfigService;


    @PostMapping("/getToken")
    public Result<SysTokenInfo> getToken() {
        return Result.state(iSysLoginService.getToken());
    }

    /**
     * 用户登录
     *
     * @param loginRequest 登录请求参数
     * @return
     */
    @PostMapping("/login")
    public Result<SysUser> login(@RequestBody @Valid LoginRequest loginRequest) {
        String showCaptcha = sysConfigService.getValueByKey(Constants.ConfigType.CAPTCHA_ENABLE);
        if (StrUtil.isNotEmpty(showCaptcha) && "true".equals(showCaptcha)) {
            if (StrUtil.isEmpty(loginRequest.getCaptcha())) {
                return Result.error("验证码不能为空");
            }
            String captchaKey = SysConstant.CACHE_CAPTCHA_KEY_PREFIX + loginRequest.getCaptcha().toLowerCase();
            String captcha = stringRedisTemplate.opsForValue().get(captchaKey);
            if (!Constants.ADMIN_LOGIN_NAME.equals(loginRequest.getLoginName()) && !loginRequest.getCaptcha().equalsIgnoreCase(captcha)) {
                return Result.error("验证码不正确！");
            }
            stringRedisTemplate.delete(captchaKey);
        }
        ThreadLocalHolder.setTenantId(loginRequest.getTenantId());
        SysUser sysUser = iSysLoginService.login(loginRequest);
        if (sysUser != null) {
            sysOssConfigService.init();
            return Result.state(sysUser);
        }
        return Result.error("账户密码不正确！");
    }

    /**
     * 退出登录
     *
     * @return
     */
    @PostMapping("/logout")
    public Result<Void> logout() {
        iSysLoginService.logout();
        return Result.success();
    }

    /**
     * 获取当前登录用户信息
     *
     * @return Result
     */
    @GetMapping("/getUserInfo")
    public Result<SysUser> getUserInfo() {
        return Result.state(iSysLoginService.getUserInfo());
    }
}
